{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 写一个可以将MNIST图片向任意方向（上，下，左，右）移动一个像素功能。\n",
    "### 然后对训练集中的每张图片，创建四个位移后的副本，每个方向一个，添加到训练集。\n",
    "### 最后，在这个扩展过的训练集上训练模型，衡量其在测试集上的精度，来优化精度，这种人工扩展## 练集扩展。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.datasets import fetch_mldata \n",
    "import numpy as np\n",
    "from sklearn.neighbors import KNeighborsClassifier # 读取数据集内容,\t读取本地\n",
    "mnist = fetch_mldata('mnist-original', data_home='./') \n",
    "X, y = mnist[\"data\"], mnist[\"target\"]\n",
    "# 建立测试集\n",
    "X_train,X_test,y_train,y_test=X[:60000,:],X[60000:,:],y[:60000],y[60000:]   # 重新洗牌，划分训练集\n",
    "shuffle_index = np.random.permutation(60000)\n",
    "X_train, y_train = X_train[shuffle_index], y_train[shuffle_index] \n",
    "X_train, y_train = X_train[:60000], y_train[:60000]\n",
    "train_array = []\n",
    "train_size = X_train.shape[0] # 遍历训练集 60000张图片\n",
    "for i in range(train_size):\n",
    "# 每张图片的 维度设置为 28 28\t添加到列表中\n",
    "    train_array.append(X_train[i].reshape(28, 28))\n",
    "print('train_size=', train_size)\n",
    "train_array[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 进行图片移动"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def data_en(data_s, direc='u'): \n",
    "    size=len(data_s)\n",
    "    en_ret = np.zeros((size, 784)) \n",
    "    print(size,en_ret.shape)\n",
    "    if direc == 'u':\n",
    "        for i in range(size):\n",
    "            # 定义一个空列表，我先把一块的1行之最后添加进去，，再添加第一行， \n",
    "            trans_data = np.append(data_s[i][1:,:], data_s[i][0:1,:],axis=0) \n",
    "            print(trans_data,trans_data.shape)\n",
    "            #将数据转化为一行 n列。-1在这里理解为一个正整数通配符，它代替任何整数\n",
    "            en_ret[i] = trans_data.reshape(1, -1) \n",
    "            print(en_ret[i].shape)\n",
    "    elif direc == 'd':\n",
    "        for i in range(size):\n",
    "            trans_data = np.append(data_s[i][-1:,:], data_s[i][:-1,:],axis=0) \n",
    "            #print(trans_data.shape)\n",
    "            en_ret[i] = trans_data.reshape(1, -1) \n",
    "    elif direc == 'l':\n",
    "        for i in range(size):\n",
    "            trans_data = np.append(data_s[i][:,1:], data_s[i][:,0:1],axis=1) \n",
    "            #print(trans_data.shape)\n",
    "            en_ret[i] = trans_data.reshape(1, -1) \n",
    "    elif direc == 'r':\n",
    "        for i in range(size):\n",
    "            trans_data = np.append(data_s[i][:,-1:], data_s[i][:,:-1],axis=1) \n",
    "            #plt.imshow(trans_data, cmap =matplotlib.cm.binary,interpolation=\"nearest\") \n",
    "            en_ret[i] = trans_data.reshape(1, -1)\n",
    "            \n",
    "    return en_ret\n",
    "X_trainu = data_en(train_array, 'u') \n",
    "X_traind = data_en(train_array, 'd') \n",
    "X_trainl = data_en(train_array, 'l') \n",
    "X_trainr = data_en(train_array, 'r')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 计算移动前和移动后的打分"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X_trainA = np.concatenate((X_train, X_trainu, X_traind, X_trainl, X_trainr), axis=0)\n",
    "y_trainA = np.concatenate((y_train, y_train, y_train, y_train, y_train), axis=0) \n",
    "print(X_trainA.shape)\n",
    "print(y_trainA.shape)\n",
    "# 实例化，测试训练集【移动前】\n",
    "knn_clf = KNeighborsClassifier() \n",
    "knn_clf.fit(X_train, y_train) \n",
    "y_pred = knn_clf.predict(X_test)\n",
    "from sklearn.metrics import precision_score, recall_score,confusion_matrix \n",
    "ps = precision_score(y_test, y_pred, average=None)\n",
    "print('\\nps=', ps, np.average(ps))\n",
    "# 移动后\n",
    "knn_clfA = KNeighborsClassifier() \n",
    "knn_clfA.fit(X_trainA, y_trainA) \n",
    "y_pred = knn_clfA.predict(X_test)\n",
    "psA = precision_score(y_test, y_pred, average=None) \n",
    "print('\\npsA=', psA, np.average(psA))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
